﻿using System;
using UnityEngine;

namespace Core.Setting
{
    /// <summary>
    /// 屏幕相关设置，
    /// </summary>
    public partial class ScreenSetting : AbstractSettingItem, IUpdate
    {
        //异形屏偏移量
        public Rect SafeArea { get; private set; }

        public WH Size { get; private set; }
        public WH Resolution { get; private set; }

        private IScreenPlatform platform;
        public ScreenOrientation Orientation => platform.Orientation;
        public bool IsPortrait() => platform.IsPortrait();
        public bool IsLandscape() => platform.IsLandscape();
        public void Set(ESceneOrientation ori) => platform.Set(ori);

        public event Action OnChanged;
        private Action funcPointer;

        public override void Awake()
        {
            if (S.Platform.IsEditor)
            {
                platform = G.Factory.Create<ScreenEditor>();
            }
            else if (S.Platform.IsNative)
            {
                platform = G.Factory.Create<ScreenNative>();
            }
            else if (S.Platform.IsWeChat)
            {
                platform = G.Factory.Create<ScreenWeChat>();
            }

            platform.Awake(this);
        }

        public void Update()
        {
            funcPointer?.Invoke();
        }

        public override void Dispose()
        {
            if (IsDisposed) return;
            base.Dispose();
        }

        private void Listen()
        {
            funcPointer = CheckChangedFunc;
        }

        private void CheckChangedFunc()
        {
            if (!Mathf.Approximately(Size.Width, Screen.width) || !Mathf.Approximately(Size.Height, Screen.height))
            {
                Size = new WH(Screen.width, Screen.height);
                log.err($"========   Screen.size=({Screen.width},{Screen.height}) {Screen.currentResolution}");
                OnChanged?.Invoke();
                funcPointer = null;
            }
        }

        public override void Refresh()
        {
        }
    }
}
